package com.old.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayDeque;
import java.util.Queue;

import org.apache.log4j.Logger;

public class ConnectionPool {
	private static final long serialVersionUID = 1L;
	
	public ConnectionPool(String name, String conn_string, int count, boolean readonly) {
		this.name = name;
		this.conn_string = conn_string;
		this.count = count;
		this.readonly = readonly;
	}

	public Connection GetConnection() throws DBConnException {
		ConnTime conn;
		synchronized (pool) {
			conn = pool.poll();
		}

		if (conn != null) {
			try {
				if (MyUtils.getCurrentTimeMillis() - conn.time > Constant.Hour)
					conn.conn.close();
				else if (!conn.conn.isClosed())
					return conn.conn;
			} catch (SQLException e) {
			}
		}

		try {
			Connection c = DriverManager.getConnection(conn_string);
			c.setReadOnly(readonly);
			return c;
		} catch (SQLException e) {
			log.error("get conn failed! name is " + name, e);
			throw new DBConnException(e);
		}
	}

	public void BackConnection(Connection conn) {
		if (conn == null)
			return;
		synchronized (pool) {
			if (pool.size() < count) {
				pool.add(new ConnTime(conn));
				return;
			}
		}
		try {
			conn.close();
		} catch (SQLException e) {
			log.error(name, e);
		}
	}

	public int GetSize() {
		synchronized (pool) {
			return pool.size();
		}
	}

	public String GetName() {
		return name;
	}

	public int GetCount() {
		return count;
	}

	private static transient Logger log = Logger.getLogger(ConnectionPool.class);
	private String name, conn_string;
	private int count;
	private boolean readonly;
	private Queue<ConnTime> pool = new ArrayDeque<ConnTime>();

	private class ConnTime {
		private static final long serialVersionUID = 1L;
		
		ConnTime(Connection c) {
			conn = c;
			time = MyUtils.getCurrentTimeMillis();
		}

		Connection conn;
		long time;
	}
}